<template>
  <view class="appointment-edit-container">
    <view class="page-header">
      <text class="page-title">编辑预约</text>
      <text class="page-subtitle">修改预约信息 / 添加诊断处方</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <!-- 预约信息（只读） -->
      <view class="form-section readonly-section">
        <text class="section-title">预约信息（不可修改）</text>
        
        <view class="info-item">
          <text class="info-label">预约号</text>
          <text class="info-value">{{ formatAppointmentNo(formData.appointment_no) }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">患者姓名</text>
          <text class="info-value">{{ patientName }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">医生姓名</text>
          <text class="info-value">{{ doctorName }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">预约时间</text>
          <text class="info-value highlight">{{ formData.appointment_date }} {{ formData.appointment_time }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">预计时长</text>
          <text class="info-value">{{ formatDuration(formData.duration_minutes) }}</text>
        </view>
      </view>

      <!-- 就诊信息 -->
      <view class="form-section">
        <text class="section-title">就诊信息</text>
        
        <view class="form-item">
          <text class="form-label">首复诊</text>
          <radio-group @change="onVisitTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.visit_type === 1" color="#007aff"/>
              <text class="radio-text">初诊</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.visit_type === 2" color="#007aff"/>
              <text class="radio-text">复诊</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">主诉</text>
          <textarea 
            v-model="formData.chief_complaint" 
            class="form-textarea" 
            placeholder="请输入患者主诉"
            maxlength="500"
          />
        </view>
      </view>

      <!-- 诊断与处方 -->
      <view class="form-section">
        <text class="section-title">诊断与处方（医生填写）</text>
        
        <view class="form-item">
          <text class="form-label">诊断结果</text>
          <textarea 
            v-model="formData.diagnosis" 
            class="form-textarea" 
            placeholder="请输入诊断结果"
            maxlength="1000"
          />
        </view>

        <view class="form-item">
          <text class="form-label">处方内容</text>
          <textarea 
            v-model="formData.prescription" 
            class="form-textarea" 
            placeholder="请输入处方内容"
            maxlength="1000"
          />
        </view>

        <view class="form-item">
          <text class="form-label">治疗计划</text>
          <textarea 
            v-model="formData.treatment_plan" 
            class="form-textarea" 
            placeholder="请输入治疗计划"
            maxlength="1000"
          />
        </view>
      </view>

      <!-- 支付与状态 -->
      <view class="form-section">
        <text class="section-title">支付与状态</text>
        
        <view class="form-item">
          <text class="form-label">支付状态</text>
          <radio-group @change="onPaymentStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.payment_status === 0" color="#007aff"/>
              <text class="radio-text">未支付</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.payment_status === 1" color="#007aff"/>
              <text class="radio-text">已支付</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.payment_status === 2" color="#007aff"/>
              <text class="radio-text">已退款</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item" v-if="formData.payment_status === 1">
          <text class="form-label">支付方式</text>
          <radio-group @change="onPaymentMethodChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.payment_method === 1" color="#007aff"/>
              <text class="radio-text">微信支付</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.payment_method === 2" color="#007aff"/>
              <text class="radio-text">支付宝</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.payment_method === 3" color="#007aff"/>
              <text class="radio-text">现金</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">预约状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.status === 1" color="#007aff"/>
              <text class="radio-text">已预约</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.status === 2" color="#007aff"/>
              <text class="radio-text">已就诊</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.status === 3" color="#007aff"/>
              <text class="radio-text">未到诊</text>
            </label>
            <label class="radio-item">
              <radio value="4" :checked="formData.status === 4" color="#007aff"/>
              <text class="radio-text">已取消</text>
            </label>
            <label class="radio-item">
              <radio value="5" :checked="formData.status === 5" color="#007aff"/>
              <text class="radio-text">医生拒诊</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const appointmentId = ref('')
const patientName = ref('')
const doctorName = ref('')

const formData = reactive({
  appointment_no: '',
  patient_id: '',
  doctor_id: '',
  appointment_date: '',
  appointment_time: '',
  duration_minutes: '',
  visit_type: 1,
  chief_complaint: '',
  diagnosis: '',
  prescription: '',
  treatment_plan: '',
  payment_status: 0,
  payment_method: 0,
  status: 1
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  appointmentId.value = currentPage.options.id || ''
  
  if (!appointmentId.value) {
    uni.showToast({ title: '缺少预约ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/appointments/list' })
    }, 1500)
    return
  }
  
  await loadAppointmentData()
  pageLoading.value = false
})

async function loadAppointmentData() {
  try {
    const appointmentsObj = uniCloud.importObject('dh-appointments')
    const res = await appointmentsObj.getAppointmentById(appointmentId.value)
    
    if (res.code === 200 && res.data) {
      // 保留完整数据结构
      Object.assign(formData, {
        ...res.data,
        doctor_id: res.data.doctor_id
      })
      
      // 云函数已经返回了 patient_name 和 doctor_name
      patientName.value = res.data.patient_name || '未知用户'
      doctorName.value = res.data.doctor_name || '未知医生'
    } else {
      throw new Error(res.message || '预约不存在')
    }
  } catch (err) {
    console.error('加载预约数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/appointments/list' })
    }, 1500)
  }
}

// 格式化预约号
function formatAppointmentNo(appointmentNo) {
  if (!appointmentNo) return '暂无'
  if (appointmentNo.startsWith('APT') && appointmentNo.length >= 14) {
    const year = appointmentNo.substring(5, 7)
    const month = parseInt(appointmentNo.substring(7, 9))
    const day = parseInt(appointmentNo.substring(9, 11))
    const number = appointmentNo.substring(11)
    return `${year}年${month}月${day}日${number}号`
  }
  return appointmentNo
}

// 格式化时长
function formatDuration(minutes) {
  if (!minutes) return '暂无'
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  if (remainingMinutes === 0) {
    return `${hours}小时`
  }
  return `${hours}小时${remainingMinutes}分钟`
}

function onVisitTypeChange(e) {
  formData.visit_type = parseInt(e.detail.value)
}

function onPaymentStatusChange(e) {
  formData.payment_status = parseInt(e.detail.value)
  // 如果改为未支付或已退款，清空支付方式
  if (formData.payment_status !== 1) {
    formData.payment_method = 0
  }
}

function onPaymentMethodChange(e) {
  formData.payment_method = parseInt(e.detail.value)
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function handleCancel() {
  uni.navigateBack()
}

async function handleSubmit() {
  try {
    const updateData = {
      visit_type: formData.visit_type,
      chief_complaint: formData.chief_complaint,
      diagnosis: formData.diagnosis,
      prescription: formData.prescription,
      treatment_plan: formData.treatment_plan,
      payment_status: formData.payment_status,
      payment_method: formData.payment_method,
      status: formData.status
    }
    
    const appointmentsObj = uniCloud.importObject('dh-appointments')
    const res = await appointmentsObj.updateAppointment(appointmentId.value, updateData)
    
    if (res.code === 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: res.message || '保存失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('保存失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    })
  }
}
</script>

<style scoped>
.appointment-edit-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
}

.page-header {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.page-subtitle {
  font-size: 26rpx;
  color: #999;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f0f0f0;
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.form-section {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.readonly-section {
  background: #f8f9fa;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #e0e0e0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
  font-size: 28rpx;
  min-width: 160rpx;
}

.info-value {
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
  text-align: right;
}

.info-value.highlight {
  color: #007aff;
  font-weight: bold;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.form-label.required::before {
  content: '* ';
  color: #ff3b30;
}

.form-textarea {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background: #fafafa;
  box-sizing: border-box;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 30rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 20rpx;
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.btn {
  flex: 1;
  height: 88rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-cancel {
  background: #f0f0f0;
  color: #666;
}

.btn-primary {
  background: #007aff;
  color: white;
}
</style>
